﻿//Copyright (c) 2009, Offbeat Guides
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are 
//permitted provided that the following conditions are met:
//
//* Redistributions of source code must retain the above copyright notice, this list of 
//conditions and the following disclaimer.
//
//* Redistributions in binary form must reproduce the above copyright notice, this list 
//of conditions and the following disclaimer in the documentation and/or other materials 
//provided with the distribution.
//
//* Neither the name of Offbeat Guides nor the names of its contributors may be used to 
//endorse or promote products derived from this software without specific prior written 
//permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
//EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
//OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
//SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
//OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
//TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
//EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;
using System.IO;

namespace Amazon.Services.S3
{
    [Serializable]
    [XmlRoot("bucket", Namespace = "http://s3.amazonaws.com/doc/2006-03-01/")]
    public sealed class DriveInfo : System.Xml.Serialization.IXmlSerializable
    {
        #region Static Variables
        internal static readonly System.Int32 MinNameLength = 3;
        internal static readonly System.Int32 MaxNameLength = 255;
        #endregion

        #region Variables
        private System.String _location;

        [NonSerialized]
        private Amazon.Services.ServiceClient _client;

        [NonSerialized]
        private Amazon.Services.S3.DirectoryInfo _root;
        #endregion

        #region Properties
        public String Name { get; private set; }

        public DateTime CreationDate { get; private set; }

        public String Location
        {
            get
            {
                if (String.IsNullOrEmpty(this._location))
                    this._location = this.GetLocation();
                return this._location;
            }
        }

        public DirectoryInfo RootDirectory
        {
            get
            {
                if (this._root == null)
                    this._root = new DirectoryInfo(this._client.Account, String.Format("{0}:\\", this.Name));
                return this._root;
            }
        }
        #endregion

        #region Constructors and Finalizers
        internal DriveInfo(ServiceClient client)
        {
            this._client = client;
        }

        public DriveInfo(AmazonAccount account, String name)
            : this(new ServiceClient(account, S3Configuration.Default))
        {
            this.Name = name;
            this._location = this.GetLocation();
        }
        #endregion

        #region Methods
        private String GetLocation()
        {
            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("bucket", this.Name);
            parameters.Add("path", "?location");

            Response response = this._client.Invoke(parameters, null);

            // just some basic reader settings; mainly to prevents whitespace from being read
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            settings.IgnoreWhitespace = true;

            // tear is apart into the instances and return the list
            using (XmlReader reader = XmlTextReader.Create(new StringReader(response.Body), settings))
            {
                reader.ReadToFollowing("LocationConstraint");
                String value = reader.ReadElementString();
                return String.IsNullOrEmpty(value) ? "US" : value;
            }
        }

        public void Delete()
        {
            DriveInfo.Delete(this._client.Account, this.Name, false);
        }

        public void Delete(Boolean recursive)
        {
            DriveInfo.Delete(this._client.Account, this.Name, recursive);
        }
        #endregion

        #region IXmlSerializable Methods
        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (!reader.Name.Equals("bucket", StringComparison.OrdinalIgnoreCase))
                reader.ReadToFollowing("bucket");

            reader.ReadStartElement();
            {
                while (!reader.Name.Equals("bucket", StringComparison.OrdinalIgnoreCase) || reader.NodeType != XmlNodeType.EndElement)
                {
                    switch (reader.Name.ToLower())
                    {
                        case "name":
                            this.Name = reader.ReadElementString();
                            break;
                        case "creationdate":
                            this.CreationDate = DateTime.Parse(reader.ReadElementString());
                            break;
                        default:
                            reader.ReadOuterXml();
                            break;
                    }
                }
            }
            reader.ReadEndElement();
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Overriden Methods
        public override string ToString()
        {
            return this.Name;
        }
        #endregion

        #region Static Methods
        public static DriveInfo Create(AmazonAccount account, String name)
        {
            // more needs to be done, but the method should validate the name agains the DNS-compatible naming conventions
            if (name.Length < 3 || name.Length > 63)
                throw new ArgumentOutOfRangeException("Drive name must be between 3 and 63 characters long.");

            // create parameters for the request
            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("bucket", name);
            parameters.Add("method", "PUT");

            ServiceClient client = new ServiceClient(account, S3Configuration.Default);
            Response response = client.Invoke(parameters, null);
            if (response.Status != System.Net.HttpStatusCode.OK)
                throw new IOException("Unable to create drive");

            FileSystemHelper.CreateFile(client, name, FileSystemHelper.ToDirectory(String.Empty));

            DriveInfo[] drives = DriveInfo.GetDrives(account);
            for (int i = 0; i < drives.Length; i++)
            {
                if (drives[i].Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                    return drives[i];
            }
            return null;
        }

        public static void Delete(AmazonAccount account, String name)
        {
            DriveInfo.Delete(account, name, false);
        }

        public static Boolean Exists(AmazonAccount account, String name)
        {
            DriveInfo[] drives = DriveInfo.GetDrives(account);
            for (int i = 0; i < drives.Length; i++)
                if (drives[i].Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                    return true;
            return false;
        }

        public static void Delete(AmazonAccount account, String name, Boolean recursive)
        {
            // delete the directories that are part of this drive
            Directory.Delete(account, String.Format("{0}:\\", name), recursive);

            // create parameters for the request
            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("bucket", name);
            parameters.Add("method", "DELETE");

            ServiceClient client = new ServiceClient(account, S3Configuration.Default);
            Response response = client.Invoke(parameters, null);
            if (response.Status != System.Net.HttpStatusCode.NoContent)
                throw new IOException("Unable to delete drive");
        }

        public static DriveInfo[] GetDrives(AmazonAccount account)
        {
            List<DriveInfo> drives = new List<DriveInfo>();

            ServiceClient client = new ServiceClient(account, S3Configuration.Default);
            Response response = client.Invoke(new Dictionary<String, String>(), null);

            // just some basic reader settings; mainly to prevents whitespace from being read
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            settings.IgnoreWhitespace = true;

            // tear is apart into the instances and return the list
            using (XmlReader reader = XmlTextReader.Create(new StringReader(response.Body), settings))
            {
                while (reader.ReadToFollowing("Buckets"))
                {
                    reader.ReadStartElement("Buckets");
                    {
                        while (reader.Name.Equals("Bucket", StringComparison.OrdinalIgnoreCase) && reader.NodeType != XmlNodeType.EndElement)
                        {
                            DriveInfo drive = new DriveInfo(client);
                            (drive as IXmlSerializable).ReadXml(reader);
                            drives.Add(drive);
                        }
                    }
                    reader.ReadEndElement();
                }
            }

            return drives.ToArray();
        }
        #endregion
    }
}
